package yl.hs.bmipfull.security;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * @author 谢景广
 * @category AES加密工具
 */
public class Aes {
    private static final String KEY = "H%u$a*S&ha998I;n";
    private static final String IV = "X&(G*&^%#$^QHJC8";

    /**
     * 通过字典加密
     *
     * @param sSrc 需要加密的字符串
     * @param key  加密字典
     * @return 加密后的字符串
     */
    public static String encrypt(String sSrc, String key) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
        byte[] raw = KEY.getBytes(StandardCharsets.UTF_8);
        SecretKeySpec sKeySpec = new SecretKeySpec(raw, "AES");
        // "算法/模式/补码方式"
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        // 使用CBC模式，需要一个向量iv，可增加加密算法的强度
        IvParameterSpec iv = new IvParameterSpec(IV.getBytes(StandardCharsets.UTF_8));
        cipher.init(Cipher.ENCRYPT_MODE, sKeySpec, iv);
        byte[] encrypted = cipher.doFinal(sSrc.getBytes(StandardCharsets.UTF_8));
        // 此处使用BAES64做转码功能，同时能起到2次加密的作用。

        return parseByte2HexStr(encrypted).toUpperCase();
    }

    /**
     * 将二进制转换成16进制
     *
     * @param buf 二进制字节数组
     * @return 十六进制字符串
     */
    public static String parseByte2HexStr(byte[] buf) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    /**
     * 将16进制转换为二进制
     *
     * @param hexStr 十六进制字符串
     * @return 二进制字节数组
     */
    public static byte[] parseHexStr2Byte(String hexStr) {
        try {
            if (hexStr.length() < 1) {
                return null;
            }
            byte[] result = new byte[hexStr.length() / 2];
            for (int i = 0; i < hexStr.length() / 2; i++) {
                int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
                int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
                result[i] = (byte) (high * 16 + low);
            }
            return result;
        } catch (Exception ex) {
            return null;
        }
    }

    /**
     * 通过字典解密
     *
     * @param sSrc 需要解密的字符串
     * @param key  字典
     * @return 解密后的结果
     */
    public static String decrypt64(String sSrc, String key) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {

        byte[] raw = KEY.getBytes(StandardCharsets.UTF_8);
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        IvParameterSpec iv = new IvParameterSpec(IV.getBytes(StandardCharsets.UTF_8));
        cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);


        Base64 base64 = new Base64();
        byte[] encrypted1 = base64.decode(sSrc);
        if (encrypted1 != null) {
            byte[] original = cipher.doFinal(encrypted1);
            String originalString = new String(original, StandardCharsets.UTF_8);
            return originalString;
        }
        return "";
    }

    /**
     * 通过字典解密
     *
     * @param sSrc 需要解密的字符串
     * @param key  字典
     * @return 解密后的结果
     */
    public static String decrypt(String sSrc, String key) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
        byte[] raw = KEY.getBytes(StandardCharsets.UTF_8);
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        IvParameterSpec iv = new IvParameterSpec(IV.getBytes(StandardCharsets.UTF_8));
        cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
        byte[] encrypted1 = parseHexStr2Byte(sSrc);
        if (encrypted1 != null) {
            byte[] original = cipher.doFinal(encrypted1);
            String originalString = new String(original, StandardCharsets.UTF_8);
            return originalString;
        }
        return "";
    }

    /**
     * 加密
     *
     * @param source 需要加密的字符串
     * @return 加密后的结果
     */
    public static String encrypt(String source) throws Exception {
        return encrypt(source, KEY);
    }

    /**
     * 解密
     *
     * @param source 需要解密的字符串
     * @return 解密后的结果
     */
    public static String decrypt(String source) throws Exception {
        return decrypt(source, KEY);
    }

    /**
     * 解密
     *
     * @param source 需要解密的字符串
     * @return 解密后的结果
     */
    public static String decrypt64(String source) throws Exception {
        return decrypt64(source, KEY);
    }
}
